'use client'

import React, { createContext, useContext, useEffect, ReactNode } from 'react'
import { useImageStore } from '@/stores/imageStore'
import { useUIStore } from '@/stores/uiStore'
import { useTaskStore } from '@/stores/taskStore'

// Store Provider Context
interface StoreContextType {
    imageStore: ReturnType<typeof useImageStore>
    uiStore: ReturnType<typeof useUIStore>
    taskStore: ReturnType<typeof useTaskStore>
}

const StoreContext = createContext<StoreContextType | null>(null)

// Store Provider Props
interface StoreProviderProps {
    children: ReactNode
}

// Store Provider Component
export const StoreProvider: React.FC<StoreProviderProps> = ({ children }) => {
    const imageStore = useImageStore()
    const uiStore = useUIStore()
    const taskStore = useTaskStore()

    // 初始化应用状态
    useEffect(() => {
        const initializeApp = async () => {
            try {
                // 设置全局加载状态
                uiStore.setGlobalLoading(true)

                // 初始化图像存储配置
                imageStore.updateConfig({
                    enableCache: true,
                    cacheTimeout: 5 * 60 * 1000, // 5分钟
                    retryAttempts: 3
                })

                // 初始化任务存储配置
                taskStore.updateConfig({
                    autoRetry: true,
                    maxRetryAttempts: 3,
                    retryDelay: 5000,
                    enableLogging: process.env.NODE_ENV === 'development',
                    pollingInterval: 2000
                })

                // 初始化UI偏好设置
                const savedTheme = localStorage.getItem('app-theme') as 'light' | 'dark' | 'auto'
                if (savedTheme) {
                    uiStore.setTheme(savedTheme)
                }

                // 加载初始数据集（如果需要）
                if (process.env.NODE_ENV === 'development') {
                    try {
                        await imageStore.loadDatasets()
                    } catch (error) {
                        console.warn('Failed to load initial datasets:', error)
                        // 在开发环境中，如果API不可用，不阻塞应用启动
                    }
                }

                // 添加成功通知
                uiStore.addNotification({
                    type: 'success',
                    title: '应用初始化完成',
                    message: '医学影像处理平台已准备就绪',
                    duration: 3000
                })

            } catch (error) {
                console.error('App initialization failed:', error)

                // 添加错误通知
                uiStore.addNotification({
                    type: 'error',
                    title: '初始化失败',
                    message: '应用初始化过程中发生错误，部分功能可能不可用',
                    duration: 5000
                })
            } finally {
                // 清除全局加载状态
                uiStore.setGlobalLoading(false)
            }
        }

        initializeApp()
    }, [])

    // 监听主题变化并保存到localStorage
    useEffect(() => {
        let previousTheme = useUIStore.getState().layout.theme

        const unsubscribe = useUIStore.subscribe((state) => {
            const currentTheme = state.layout.theme

            if (currentTheme !== previousTheme) {
                localStorage.setItem('app-theme', currentTheme)

                // 应用主题到document
                if (currentTheme === 'dark') {
                    document.documentElement.classList.add('dark')
                } else if (currentTheme === 'light') {
                    document.documentElement.classList.remove('dark')
                } else {
                    // auto模式：根据系统偏好设置
                    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
                    if (prefersDark) {
                        document.documentElement.classList.add('dark')
                    } else {
                        document.documentElement.classList.remove('dark')
                    }
                }

                previousTheme = currentTheme
            }
        })

        return unsubscribe
    }, [])

    // 监听图像数据变化，自动设置查看器类型
    useEffect(() => {
        let previousImageData = useImageStore.getState().currentImageData

        const unsubscribe = useImageStore.subscribe((state) => {
            const currentImageData = state.currentImageData

            if (currentImageData !== previousImageData) {
                if (currentImageData) {
                    // 根据图像类型自动设置查看器
                    uiStore.setViewerType(currentImageData.type)

                    // 重置面板状态
                    uiStore.resetAllPanels()

                    // 设置当前选中的图像
                    uiStore.setSelectedImage(currentImageData.id)
                }

                previousImageData = currentImageData
            }
        })

        return unsubscribe
    }, [])

    // 监听任务状态变化，显示通知
    useEffect(() => {
        let previousTaskStatuses = useTaskStore.getState().taskStatuses

        const unsubscribe = useTaskStore.subscribe((state) => {
            const currentTaskStatuses = state.taskStatuses

            // 检查任务状态变化
            Object.entries(currentTaskStatuses).forEach(([taskId, status]) => {
                const prevStatus = previousTaskStatuses?.[taskId]

                if (prevStatus && prevStatus.status !== status.status) {
                    const task = state.tasks[taskId]
                    const taskName = task?.name || `任务 ${taskId}`

                    switch (status.status) {
                        case 'completed':
                            uiStore.addNotification({
                                type: 'success',
                                title: '任务完成',
                                message: `${taskName} 已成功完成`,
                                duration: 4000
                            })
                            break

                        case 'error':
                            uiStore.addNotification({
                                type: 'error',
                                title: '任务失败',
                                message: `${taskName} 执行失败: ${status.message || '未知错误'}`,
                                duration: 6000
                            })
                            break

                        case 'cancelled':
                            uiStore.addNotification({
                                type: 'warning',
                                title: '任务取消',
                                message: `${taskName} 已被取消`,
                                duration: 3000
                            })
                            break
                    }
                }
            })

            previousTaskStatuses = currentTaskStatuses
        })

        return unsubscribe
    }, [])

    // 错误处理：监听存储错误并显示通知
    useEffect(() => {
        let previousImageErrors = useImageStore.getState().errors
        let previousTaskErrors = useTaskStore.getState().errors

        // 监听图像存储错误
        const unsubscribeImageErrors = useImageStore.subscribe((state) => {
            const currentErrors = state.errors

            Object.values(currentErrors).forEach(error => {
                if (error && !Object.values(previousImageErrors).includes(error)) {
                    uiStore.addNotification({
                        type: 'error',
                        title: '数据加载错误',
                        message: error.message,
                        duration: 5000
                    })
                }
            })

            previousImageErrors = currentErrors
        })

        // 监听任务存储错误
        const unsubscribeTaskErrors = useTaskStore.subscribe((state) => {
            const currentErrors = state.errors

            Object.values(currentErrors).forEach(error => {
                if (error && !Object.values(previousTaskErrors).includes(error)) {
                    uiStore.addNotification({
                        type: 'error',
                        title: '任务执行错误',
                        message: error.message,
                        duration: 5000
                    })
                }
            })

            previousTaskErrors = currentErrors
        })

        return () => {
            unsubscribeImageErrors()
            unsubscribeTaskErrors()
        }
    }, [])

    // 清理函数：组件卸载时清理资源
    useEffect(() => {
        return () => {
            // 停止所有任务状态轮询
            useTaskStore.getState().runningTasks.forEach(taskId => {
                useTaskStore.getState().stopStatusPolling(taskId)
            })

            // 清理缓存（可选）
            if (process.env.NODE_ENV === 'development') {
                useImageStore.getState().clearCache()
            }
        }
    }, [])

    const contextValue: StoreContextType = {
        imageStore,
        uiStore,
        taskStore
    }

    return (
        <StoreContext.Provider value={contextValue}>
            {children}
        </StoreContext.Provider>
    )
}

// Hook to use store context
export const useStores = (): StoreContextType => {
    const context = useContext(StoreContext)
    if (!context) {
        throw new Error('useStores must be used within a StoreProvider')
    }
    return context
}

// Individual store hooks for convenience
export const useImageStoreContext = () => {
    const { imageStore } = useStores()
    return imageStore
}

export const useUIStoreContext = () => {
    const { uiStore } = useStores()
    return uiStore
}

export const useTaskStoreContext = () => {
    const { taskStore } = useStores()
    return taskStore
}

export default StoreProvider